{% macro metric_table(metric_name, data, row_limit=3) -%}
{% if data %}
  <table class="table table-striped table-bordered metric table-condensed">
    <thead>
      <tr>
        <th>{{ metric_name }}</th>
        <th>Count</th>
      </tr>
    </thead>
    {% for row, cnt in data %}
      {% set row_class = "package" %}
      {% if loop.index is odd %}
        {% set row_class = row_class + " stripe" %}
      {% endif %}
      {% if loop.index > row_limit and data|length > row_limit + 1 %}
        {% set row_class = row_class + " hide" %}
      {% endif %}
      <tr class="{{ row_class }}">
        <td>{{ row }}</td>
        <td class="cell-count">{{ cnt|readable_int }}</td>
      </tr>
      {% if data|length > row_limit+1 and loop.index == row_limit %}
        <tr>
          <td colspan="2" class="text-center">
            <a href="#" class="btn-more">Show more… ({{ data|length - row_limit }})</a>
          </td>
        </tr>
      {% endif %}
    {% endfor %}
  </table>
{% endif %}
{%- endmacro %}

{% macro unique_metric_table(metric_name, data, row_limit=3) -%}
{% if data %}
  <table class="table table-striped table-bordered metric table-condensed">
    <thead>
      <tr>
        <th>{{ metric_name }}</th>
        <th class="text-nowrap">Unique / Total count</th>
      </tr>
    </thead>
    {% for name, cnt in data.items() %}

      <tr class="package {%- if loop.index > row_limit and data|length > row_limit+1 %} hide {%- endif %}">
        <td>{{ name }}</td>
        <td class="cell-count">{{ cnt.unique|readable_int }} / {{ cnt.count|readable_int }}</td>
      </tr>
      {% if data|length > row_limit+1 and loop.index == row_limit %}
        <tr>
          <td colspan="2" class="text-center">
            <a href="#" class="btn-more">Show more… ({{ data|length - row_limit }})</a>
          </td>
        </tr>
      {% endif %}
    {% endfor %}
  </table>
{% endif %}
{%- endmacro %}

{% macro package_counts_table(data, row_limit=3) -%}
{% if data %}
  <table class="table table-bordered counts-table table-condensed" data-sort-col="2" data-sort-order="desc" data-versions-shown="0">
    <thead>
      <tr class="stripe">
        <th colspan="2" class="text-right"><button class="btn btn-default btn-xs btn-toggle-versions">Show versions</button></th>
      </tr>
      <tr class="stripe">
        <th><a href="#" class="btn-sort-packages">Related packages</a> <i class="sort-indicator sort-1-desc hide fa fa-sort-alpha-desc"></i><i class="sort-indicator sort-1-asc hide fa fa-sort-alpha-asc"></i></th>
        <th><a href="#" class="btn-sort-count">Count</a> <i class="sort-indicator sort-2-desc fa fa-sort-numeric-desc"></i><i class="sort-indicator sort-2-asc hide fa fa-sort-numeric-asc"></i></th>
      </tr>
    </thead>
    <tbody>
      {% for name, cnt, versions in data %}
        {% set row_class = "package" %}
        {% if loop.index is odd %}
          {% set row_class = row_class + " stripe" %}
        {% endif %}
        {% if loop.index > row_limit and data|length > row_limit + 1 %}
          {% set row_class = row_class + " hide" %}
        {% endif %}
        <tr class="{{ row_class }}">
          <td>{{ name }}</td>
          <td class="cell-count">{{ cnt|readable_int }}</td>
        </tr>
        {% for version, cnt in versions %}
          <tr class="version hide">
            <td>&ensp;{{version}}</td>
            <td class="cell-count">{{ cnt|readable_int }}</td>
          </tr>
        {% endfor %}
        {% if data|length > row_limit+1 and loop.index == row_limit %}
          <tr>
            <td colspan="2" class="text-center">
              <a href="#" class="btn-more">Show more… ({{ data|length - row_limit }})</a>
            </td>
          </tr>
        {% endif %}
      {% endfor %}
    </tbody>
  </table>
{% endif %}
{%- endmacro %}

{% macro release_graph(history, releases, unique) -%}
    <div id="release_graph{% if unique %}_unique{% endif %}" class="col-md-6 graph"></div>
    <script>
        var rows = [
          {%- for event in history %}
              [({{ event.count }} {% if unique %} - {{ event.unique|default('0',true) }}{% endif %}),
                {{ event.unique }},
                {{ event.opsysrelease_id}}
              ],
            {%- endfor -%}
          ];

        var by_osr_id = {};
        var unique = {};
        var row;
        for(var i = 0; i < rows.length; i++) {
            row = rows[i];
            if(!(row[2] in by_osr_id)) {
                by_osr_id[row[2]] = Number(row[0]);
            }else{
                by_osr_id[row[2]] += Number(row[0]);
            }

            {% if unique %}
                if(!(row[2] in unique )) {
                    unique[row[2]] = Number(row[1]);
                }else{
                    unique[row[2]] += Number(row[1]);
                }
            {% endif %}
        }

        var data = [];
        var rightColors = getColors({{ releases|length }});
        var colorCnt = 0;

        {% for release, count in releases %}
            {% if unique %}
                var alternativeColor = LightenDarkenColor(rgbToHex(rightColors[colorCnt].r,rightColors[colorCnt].g,rightColors[colorCnt].b), -40);
                data.push({
                    label: "{{release}} - Unique",
                    data: unique[{{release.opsysrelease_id}}],
                    color: alternativeColor,
                })
            {% endif %}

            data.push({
                label: "{{release}}" {% if unique %} + " - Recurrence" {% endif %},
                data: by_osr_id[{{release.opsysrelease_id}}],
                color: rightColors[colorCnt],
            })
            colorCnt += 1;
        {% endfor %}

        var pie_chart_options =  {
            series: {
                pie: {
                    show: true,
                },
            },
            {% if unique %}
                //legend is in graph, this move legend out
                legend: {
                    margin: [-10,0]
                }
            {% endif %}
        };

        $.plot($('#release_graph{% if unique %}_unique{% endif %}'), data, pie_chart_options);
    </script>
{%- endmacro %}

{% macro history_graph(history, frequency, period, unique) -%}
  {% if not history['by_opsys'] %}
  <div class="graph graph_no_data">
    <p>No reports in the last {{ history['period_count'] }} {{ period }}s.</p>
  </div>
  {% else %}
  <div id="graph_{{ frequency }}{% if unique %}_unique{% endif %}"
       class="graph history_graph"
       data-frequency="{{ frequency }}"
       data-history="{{ history|tojson|forceescape }}"
       data-show-unique="{{ unique|int }}"
  ></div>
  {% endif %}
{%- endmacro %}

{% macro backtrace_table_columns(frame, type) -%}
<td>
{% if frame.nice_order %}
  {{ frame.nice_order }}
{% else %}
  {{ frame.order }}
{% endif %}
</td>
<td>
  <div class="crash-fn-container">
{% if not frame.reliable %}
    <div class="crash-fn">
      <abbr title="Unreliable frame">?</abbr>
{% endif %}
{% if frame.symbolsource.symbol.nice_name %}
      {{ frame.symbolsource.symbol.nice_name }}
{% else %}
      {{ frame.symbolsource.symbol.name }}
{% endif %}
{% if frame.inlined %}
      (inlined)
{% endif %}
    </div>
    <a class="expander" hidden href="#"></a>
  </div>
</td>
{% if type != 'python' %}
  <td>{{ frame.symbolsource.path }}</td>
{% endif %}
<td>
  {%- if frame.symbolsource.source_path %}
    <abbr title="{{ frame.symbolsource.offset|memory_address }} Build id: {{frame.symbolsource.build_id}}">{{ frame.symbolsource.source_path }}</abbr>
  {%- elif frame.symbolsource.offset %}
    {{ frame.symbolsource.offset|memory_address }}
    {%- if frame.symbolsource.build_id %}
      <br/>Build id: {{frame.symbolsource.build_id}}
    {%- endif %}
  {%- endif %}
</td>
<td>
  {%- if frame.symbolsource.line_number %}
    {%- if frame.symbolsource.func_offset %}
      <abbr title="{{frame.symbolsource.func_offset|memory_address}}">{{ frame.symbolsource.line_number}}</abbr>
    {%- else %}
      {{ frame.symbolsource.line_number}}
    {%- endif %}
  {%- else %}
    {{ frame.symbolsource.func_offset|memory_address or '-' }}
  {%- endif %}
</td>
{%- endmacro %}

{% macro show_backtrace(backtrace, type, oops) -%}
<table class="table table-striped table-bordered table-condensed">
  <thead>
  <tr>
    <th>Frame #</th>
    <th>Function</th>
    {% if type != 'python' %}
      <th>Binary</th>
    {% endif %}
    <th>Source or offset</th>
    <th>Line</th>
  </tr>
  </thead>
  {% for frame in backtrace %}
    <tr>
      {{ backtrace_table_columns(frame, type) }}
    </tr>
  {% endfor %}
</table>

{% if type == 'kerneloops' and oops %}
  <pre>{{ oops }}</pre>
{% endif %}
{%- endmacro %}


{% macro external_bugs(associated_id, bugs, add_delete_btn=false) -%}
{% for bug in bugs %}
  <div class="btn-group btn-group-xs" role="group">
    {% if add_delete_btn %}
    <button class="btn btn-danger" data-toggle="modal" data-target="#delBzBugModal" data-bugid="{{ bug.id }}"><span class="pficon pficon-delete"></span></button>
    {% endif %}
    <a class="btn btn-link external-bgz-btn"
      title="{{ bug.status }}{% if bug.status == "CLOSED" %} {{ bug.resolution }}{% endif %}: {{ bug.summary }}"
      href="{{ bug.url }}">{% if bug.status == "CLOSED" %}<del>{{ bug }}</del>{% else %}{{ bug }}{% endif %}
    </a>
  </div>
{% endfor %}
{% if add_delete_btn %}
<div class="modal fade" id="delBzBugModal" tabindex="-1" role="dialog" aria-labelledby="maildata-modal"
  aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h1 class="modal-title" id="maildata-modal">Dissociate bug</h1>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <form class="form-inline" enctype="multipart/form-data"
          action="{{ url_for('reports.dissociate_bug', report_id=associated_id) }}" method="POST">
          <input type="hidden" class="form-control" id="bug_id" name="bug_id" type="text" value="">
          <button type="submit" class="btn btn-primary">Proceed</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  $('#delBzBugModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var bugID = button.data('bugid') // Extract info from data-* attributes
    var modal = $(this)
    modal.find('.modal-title').text('Dissociate bug #' + bugID)
    modal.find('.modal-body').text('Do you really want to dissociate bug #' + bugID + ' from the report?')
    modal.find('.modal-footer form input').val(bugID)
  })
</script>
{% endif %}
{%- endmacro %}

{% macro external_urls(urls) -%}
{% for report_url in urls %}
    {% for url_obj in report_url %}
      <li><a
        href="{{ url_obj.url }}">{{ url_obj.url }}
        </a>
      </li>
    {% endfor %}
    <li class="empty-line"><hr></li>
{% endfor %}
{%- endmacro %}

{#
PAGINATOR
#}


{% macro paginator(pagination, query_count) -%}
{% if pagination.url_prev_page() %}
    <a class="btn btn-default" href="{{pagination.url_prev_page()}}">Previous page</a>
{% endif %}
{% if pagination.url_next_page(query_count) %}
    <a class="btn btn-default" href="{{pagination.url_next_page(query_count)}}">Next page</a>
{% endif %}
{%- endmacro %}


{#
FORM RENDERING
#}

{% macro render_field_default(field) -%}

    <div class="form-group {% if field.errors %}has-error{% endif %} {{ kwargs.pop('class_', '') }}">
        {% if (field.type != 'HiddenField' or field.type !='CSRFTokenField') %}
            {{ field.label }}
        {% endif %}

        <div class="input-group">
        {% if (field.type == 'DaterangeField') %}
            <div class="input-group-addon">
              <span class="glyphicon glyphicon-calendar"></span>
            </div>
        {% endif %}

        {{ field(class_='form-control', **kwargs) }}

        </div>
        {% if field.description %}
          <p class="help-block">
            {{field.description}}
          </p>
        {% endif %}
        {% if field.errors %}
            {% for e in field.errors %}
                <p class="help-block">{{ e }}</p>
            {% endfor %}
        {% endif %}
    </div>
{%- endmacro %}

{# Renders checkbox fields since they are represented differently in bootstrap
    Params:
        field - WTForm field (there are no check, but you should put here only BooleanField.
        kwargs - pass any arguments you want in order to put them into the html attributes.
        There are few exceptions: for - for_, class - class_, class__ - class_

    Example usage:
        {{ macros.render_checkbox_field(form.remember_me) }}
 #}
{% macro render_checkbox_field(field) -%}
    <div class="checkbox">
        <label>
            {{ field(type='checkbox', **kwargs) }} {{ field.label }}
        </label>
    </div>
    {% if field.description %}
      <p class="help-block">
        {{field.description}}
      </p>
    {% endif %}
{%- endmacro %}

{# Renders radio field
    Params:
        field - WTForm field (there are no check, but you should put here only BooleanField.
        kwargs - pass any arguments you want in order to put them into the html attributes.
        There are few exceptions: for - for_, class - class_, class__ - class_

    Example usage:
        {{ macros.render_radio_field(form.answers) }}
 #}
{% macro render_radio_field(field) -%}
    {% for value, label, _ in field.iter_choices() %}
        <div class="radio">
            <label>
                <input type="radio" name="{{ field.id }}" id="{{ field.id }}" value="{{ value }}">{{ label }}
            </label>
        </div>
    {% endfor %}
    {% if field.description %}
      <p class="help-block">
        {{field.description}}
      </p>
    {% endif %}
{%- endmacro %}

{% macro render_field(f) -%}
    {% if f.type == 'BooleanField' %}
        {{ render_checkbox_field(f, **kwargs) }}
    {% elif f.type == 'RadioField' %}
        {{ render_radio_field(f, **kwargs) }}
    {% else %}
        {{ render_field_default(f, **kwargs) }}
    {% endif %}
{%- endmacro %}

{# Renders WTForm in bootstrap way. There are two ways to call function:
     - as macros: it will render all field forms using cycle to iterate over them
     - as call: it will insert form fields as you specify:
     e.g. {% call macros.render_form(form, action_url=url_for('login_view'), action_text='Login',
                                        class_='login-form') %}
                {{ macros.render_field(form.email, placeholder='Input email', type='email') }}
                {{ macros.render_field(form.password, placeholder='Input password', type='password') }}
                {{ macros.render_checkbox_field(form.remember_me, type='checkbox') }}
            {% endcall %}

     Params:
        form - WTForm class
        action_url - url where to submit this form
        action_text - text of submit button
        class_ - sets a class for form
    #}
{% macro render_form(form, action_url='', action_text='Submit', class_='', btn_class='btn btn-default') -%}

    <form method="POST" action="{{ action_url }}" role="form" class="{{ class_ }}">
        {{ form.hidden_tag() if form.hidden_tag }}
        {% if caller %}
            {{ caller() }}
        {% else %}
            {% for f in form %}
                {% if f.type == 'BooleanField' %}
                    {{ render_checkbox_field(f) }}
                {% elif f.type == 'RadioField' %}
                    {{ render_radio_field(f) }}
                {% else %}
                    {{ render_field(f) }}
                {% endif %}
            {% endfor %}
        {% endif %}
        <button type="submit" class="{{ btn_class }}">{{ action_text }} </button>
    </form>
{%- endmacro %}
